package com.idea.relax.log.listener;

import com.idea.relax.log.props.RelaxLogProperties;
import com.idea.relax.log.support.utils.LoggingUtil;
import com.idea.relax.log.support.utils.StringPool;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

/**
 * @author: 沉香
 * @date: 2022/12/18
 * @description: 服务启动后关闭控制台日志的监听
 */
@AllArgsConstructor
@ConditionalOnProperty(
        value = {"relax.log.enabled", "relax.log.console-log.enabled"},
        havingValue = "true"
)
public class WebServerStartedAfterListener {

    private final RelaxLogProperties properties;

    @Async
    @Order
    @EventListener(WebServerInitializedEvent.class)
    public void webServerStartedAfter() {
        RelaxLogProperties.ConsoleLog props = properties.getConsoleLog();
        String removed = System.getProperty("relax.console-log.close-console-log", "false");
        if (StringPool.FALSE.equals(removed) && props.isCloseOnRunAfter()) {
            String appenderName = props.getAppenderName();
            LoggingUtil.detachAppender(appenderName);
            System.setProperty("relax.console-log.close-console-log", "true");
        }
    }

}
